package com.hu.hfaiagent.app;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.hu.hfaiagent.advisor.MyLoggerAdvisor;
import com.hu.hfaiagent.advisor.ReReadingAdvisor;
import com.hu.hfaiagent.chatmemory.FileBasedChatMemory;
import com.hu.hfaiagent.rag.QueryRewriter;
import com.hu.hfaiagent.rag.TravelAppRagCustomAdvisorFactory;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Consumer;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Slf4j
@Component
public class TravelApp {
    private final ChatClient chatClient;

    private  static final String SYSTEM_PROMPT="你是一个专业的“旅游规划大师”AI助手，能够根据用户的时间、预算、兴趣和出行偏好，定制个性化的旅行行程。" +
            "你可以：推荐适合的目的地和景点;安排详细的日程（含交通、住宿、游玩顺序）;提供本地美食、文化和实用建议;根据用户反馈快速调整行程。" +
            "你的语气亲切、专业，回答简洁清晰。" +
            "遇到信息不完整时，主动提出关键问题引导用户补充。" +
            "目标是帮助用户高效规划旅程，享受轻松愉快的旅行体验。";
    /**
     * AI客户端
     */

    public TravelApp(ChatModel dashscopeChatModel){
        String fileDir = System.getProperty("user.dir") + "/tmp/chat-memory";
        ChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory)
                )
                .build();
    }

/*
* AI
* 对话支持10次记忆
* */
    public String doChat(String message,String chatId){
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY,chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY,10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}",content);
        return content;
    }
    record TravelReport(String title, List<String> suggestions) {

    }
    /**
     * AI 旅游规划报告功能（实战结构化输出）
     *
     * @param message
     * @param chatId
     * @return
     */
    public TravelReport doChatWithReport(String message, String chatId) {
        TravelReport ravelReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成旅游规划结果，标题为{用户名}的旅游规划报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY,chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY,10))
                .call()
                .entity(TravelReport.class);
        log.info("TravelReport: {}", ravelReport);
        return ravelReport;
    }

    @Resource
    private VectorStore travelAppVectorStore;

    @Resource
    private Advisor travelAppRagCloudAdvisor;

    @Resource
    private VectorStore pgVectorVectorStore;

    @Resource
    private QueryRewriter queryRewriter;

    public String doChatWithRag(String message, String chatId) {
        String rewrittenMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(rewrittenMessage )
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors()
                // 本地知识库问答
                .advisors(new QuestionAnswerAdvisor(travelAppVectorStore))
                // 云知识库问答
                //.advisors(travelAppRagCloudAdvisor)
                //RAG检索增强
                //.advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                //检索过滤和异常处理(有点问题，暂时不用）
                //.advisors(TravelAppRagCustomAdvisorFactory.createTravelAppRagCustomAdvisor(travelAppVectorStore,"团体"))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


}
